#include "stdafx.h"

#include <MyControls/FillTool.h>
#include <MyControls/MaskEditor.h>
#include <raster/floodfill.h>

namespace My {

FillTool::FillTool(MaskEditor & owner)
	: m_Owner(owner)
{
	VERIFY (m_Cursor = AfxGetApp()->LoadCursor("FILLTOOL"));
}

bool FillTool::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
	SetCursor(m_Cursor);
	return true;
}

struct SetBit {
	bool value;
	SetBit(bool b) : value(b) { }
	void operator () (BitMask & mask, img::size_type x, img::size_type y)
		{ mask(x, y) = value; }
};

struct EqualsBit {
	bool value;
	EqualsBit(bool b) : value(b) { }
	bool operator () (BitMask & mask, img::size_type x, img::size_type y)
		{ return mask(x, y) == value; }
};

void FillTool::OnLButtonDown(UINT nFlags, CPoint p)
{
	point<int> ip = m_Owner.GetBench().ClientToBench(p);
	Extent dim = m_Owner.GetDim();
	if (ip.x >= 0 && ip.x < int(dim.sx)
		&& ip.y >= 0 && ip.y < int(dim.sy))
	{
		CWaitCursor wait;
		img::size_type x(ip.x), y(ip.y);
		raster::floodfill(m_Owner.GetBuffer(), x, y, EqualsBit(true), SetBit(true));
		m_Owner.Synchronize("Fill");
		m_Owner.GetBench().InvalidateBench();
	}
}

void FillTool::OnRButtonDown(UINT nFlags, CPoint p)
{
	point<int> ip = m_Owner.GetBench().ClientToBench(p);
	Extent dim = m_Owner.GetDim();
	if (ip.x >= 0 && ip.x < int(dim.sx)
		&& ip.y >= 0 && ip.y < int(dim.sy))
	{
		CWaitCursor wait;
		img::size_type x(ip.x), y(ip.y);
		raster::floodfill(m_Owner.GetBuffer(), x, y, EqualsBit(false), SetBit(false));
		m_Owner.Synchronize("Fill");
		m_Owner.GetBench().InvalidateBench();
	}
}

} // My